package org.su.generalmvc;

import org.su.generalmvc.core.*;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by yangchuan on 15/6/1.
 */
public class DefaultDispather {

    private IXsshApplicationContext xsshContext = null;


    /**
     * 写在全局环境
     */
    public void destroy() {
        if (!xsshContext.isSpringContext()) {
            LifeCycleManager.getInstence().destroy();
        }

        xsshContext.destroy();
    }


    /**
     * 分发方法处理器
     * @param request
     * @param response
     * @return  分配处理成功则返回true 否则返回false
     * @throws IOException
     */
    public boolean dispath(ServletRequest request, ServletResponse response) throws IOException {

        String path = ((HttpServletRequest)request).getRequestURI();

        ActionProxy ap = xsshContext.getActions().get(path);
        if (ap != null) {
            new DefaultActionInvocation(ap, request, response)
                    .parseRequest();
            return true;
        } else {
            //chain.doFilter(request, response);
            return false;
        }

    }

    /**
     * 初始化系统环境
     * @param serviceContext
     * @throws Exception
     */
    public void init(IServiceContext serviceContext,String configPath) throws Exception {
        if (xsshContext == null) {
            InitialContext.getInstance().init(configPath, serviceContext);
            xsshContext = InitialContext.getInstance().getContext();
        }

    }


}
